/**
 * 
 */
package com.cipe.cmrs.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cipe.cmrs.model.Donor;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.util.DateUtil;

/**
 * @author Incepio
 * 
 */
@Service
@Transactional
public class DonorService extends BaseService<Donor> {

	@Autowired
	private UserService	userService;

	public Donor saveDonor(Donor donor, Integer userId) {
		if (donor != null) {
			User user = userService.findById(userId);
			Donor dbDonor = findById(donor.getId());
			if (dbDonor == null) {
				dbDonor = new Donor();
				dbDonor.setCreatedBy(user);
				dbDonor.setCreationDate(DateUtil.getCurrentDate());
			}
			dbDonor.setDonorAcronym(donor.getDonorAcronym());
			dbDonor.setDonorName(donor.getDonorName());
			dbDonor.setUrl(donor.getUrl());
			dbDonor.setAddress1(donor.getAddress1());
			dbDonor.setAddress2(donor.getAddress2());
			dbDonor.setCity(donor.getCity());
			dbDonor.setState(donor.getState() != null && donor.getState().getId() != null ? donor.getState() : null);
			dbDonor.setZipCode(donor.getZipCode());
			dbDonor.setCountry(donor.getCountry().getId() != null ? donor.getCountry() : null );
			dbDonor.setContactName(donor.getContactName());
			dbDonor.setPhone(donor.getPhone());
			dbDonor.setFax(donor.getFax());
			dbDonor.setEmail(donor.getEmail());
			dbDonor.setUpdatedBy(user);
			dbDonor.setUpdationDate(DateUtil.getCurrentDate());
			return merge(dbDonor);
		}
		return null;
	}
	
	public List<Donor> getAllDonors() {
		return dao.getResultList("FROM Donor ORDER BY donorName ASC");
	}
	
	public boolean donorNameExists(String donorName, Integer excludeDonorId) {
		List<Donor> donors = null;
		if (excludeDonorId != null && excludeDonorId > 0) {
			donors = dao.getResultList("SELECT 1 FROM Donor WHERE UPPER(donorName) = ?1 AND id != ?2", new Object[] { donorName.toUpperCase(), excludeDonorId });
		} else {
			donors = dao.getResultList("SELECT 1 FROM Donor WHERE UPPER(donorName) = ?1", new Object[] { donorName.toUpperCase() });
		}
		return donors != null && donors.size() > 0;
	}
}
